package top.hkyzf.event;

import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.logging.LogUtils;
import net.minecraft.client.KeyMapping;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.lwjgl.glfw.GLFW;
import org.slf4j.Logger;
import top.hkyzf.util.ClientConfig;
import top.hkyzf.util.OneKeyContext;
import top.hkyzf.util.hook.OnHook;
import top.hkyzf.util.Utils;

import java.awt.event.KeyEvent;

/**
 * description: 键盘相关事件
 * @author zhufeng
 * @date 2022/8/5 13:56
 * @version V1.0
 */
@Mod.EventBusSubscriber(value = Dist.CLIENT)
public class KeyBoardEvents {
    /**
     * 获取一个 slf4j 日志记录器
     */
    private static final Logger LOGGER = LogUtils.getLogger();
    /**
     * Mod 上下文环境
     */
    private static final OneKeyContext CONTEXT = OneKeyContext.getInstance();
    /**
     * 挂机类
     */
    private static final OnHook ON_HOOK = new OnHook();
    /**
     * 创建传送键映射
     */
    public static final KeyMapping TRANSPORT_KEY = new KeyMapping(
            "key.transport",
            InputConstants.KEY_GRAVE,
            "key.category." + Utils.MOD_ID);
    /**
     * 创建挂机键映射
     */
    public static final KeyMapping ON_HOOK_KEY = new KeyMapping(
            "key.onhook",
            InputConstants.KEY_F10,
            "key.category." + Utils.MOD_ID);

    /**
     * 监听键盘输入事件
     * GLFW.GLFW_RELEASE 键盘释放事件
     * GLFW.GLFW_PRESS   键盘按下事件
     * GLFW.GLFW_REPEAT  键盘长按事件
     * KeyEvent.VK_X 和 GLFW.GLFW_KEY_X 都定义了 KeyCode 但只有部分一致
     * KeyEvent.getKeyText() 只能匹配部分 event.getKey() 数值
     * @param event 键盘输入事件
     */
    @SubscribeEvent
    public static void onKeyboardInput(InputEvent.KeyInputEvent event) {
        // 当键盘被按下则执行
        if (GLFW.GLFW_PRESS == event.getAction()) {
            LOGGER.debug(KeyEvent.getKeyText(event.getKey()) + " 键被按下了！");
            // 按下 F12 回默认家
            if (GLFW.GLFW_KEY_F12 == event.getKey()) {
                Utils.sendCommand("/home " + ClientConfig.DEFAULT_HOME.get());
            // 按下传送键回名字叫 safe 的家
            } else if (TRANSPORT_KEY.getKey().getValue() == event.getKey()) {
                Utils.sendCommand("/home " + ClientConfig.SAFE_HOME.get());
            // 按下挂机键开始挂机
            } else if (ON_HOOK_KEY.getKey().getValue() == event.getKey()) {
                // 挂机过程中再次按挂机键则停止挂机
                if (CONTEXT.isInControl()) {
                    ON_HOOK.forceStopHook();
                    LOGGER.info("挂机完毕！");
                } else {
                    ON_HOOK.onHookInNewThread();
                    LOGGER.info("另起线程开始挂机！");
                }
            }
        }
    }
}
